package com.lxh.lxhcrm.model.service;

import com.lxh.lxhcrm.model.dao.customer.*;
import com.lxh.lxhcrm.model.mappers.customer.CusMapper;
import com.lxh.lxhcrm.model.pojos.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CustomerService {
    @Autowired
    CusMapper cusMapper;


    @Autowired
    CusDao cusDao;
    @Autowired
    ContactDao conDao;
    @Autowired
    BehaviorDao behaDao;
    @Autowired
    ActionRecordDao acreDao;
    @Autowired
    BehaviorRecordDao bereDao;
    @Resource
    CusStageDao cusStageDao;
    /**
     * 查询所有客户信息（带分页）
     * @param search: 模糊查询搜索值
     * @param cusTypeName：客户类型名
     * @param stageId：客户阶段名:
     * @return: 客户对象集合
     */
    public List<Customer> allCusInfo(String search,Integer cusTypeName,Integer stageId){return cusMapper.allCusInfor(search, cusTypeName,stageId);}

    /**
     * 查询所有客户信息（不带分页）
     * @return 客户对象集合
     */
    public List<Customer>  select_cus(){return cusMapper.select_cus();};
    /**
     * 查询所有客户阶段
     * @return 客户阶段集合
     */
    public List<CusStage> allStage(){return cusMapper.allStage();};
    /**
     * 查询所有客户类型
     * @return 客户类型集合
     */
    public List<CustomerType> allCusType(){
        return cusMapper.allCusType();
    };
    /**
     * 查询所有客户来源
     * @return 客户来源集合
     */
    public List<CustomerSource> allCusSource(){return cusMapper.allCusSource();};
    /**查询所有公海*/
    public List<Sea> allSea(){return cusMapper.allSea();};
    /**查询所有联系人//带分页*/
    public List<Contact> all_linkman(){return cusMapper.all_linkman();}
    /**查询所有联系人类型*/
    public  List<ContactType> all_contact_type(){return  cusMapper.all_contact_type();};
    /**查询某客户所有联系人*/
    public  List<Contact> hisLinkman(Integer customerId){return cusMapper.hisLinkman(customerId);};
    /**查询某客户所有销售机会*/
    public  List<Opportunity> hisSaleOppo(Integer customerId){return  cusMapper.hisSaleOppo(customerId);};
    /**查询某客户所有相关行动记录*/
    public List<ActionRecord> allActionRecor(Integer customerId){return  cusMapper.allActionRecor(customerId);};

    /**时间线
     *
     * @param customerId
     * @return
     */
    public List<Map<String,Object>>  timeLine(Integer customerId){return  cusMapper.timeLine(customerId);};
    /**查询某客户所有相关合同*/
    public List<Contract> allHisContracts(Integer customerId){return cusMapper.allHisContracts(customerId);};
    /**查询某客户行为分数*/
    public List<BehaviorRecord> actionScore(Integer customerId){return  cusMapper.actionScore(customerId);};

   /**
    * 新增行动记录时,客户所处阶段改变
    * @param customer ：客户对象
    */
    public void stageChange1(Customer customer){
        CusStage cusStage = customer.getCusStage();
        int stageId = cusStage.getStageId();
        if ( stageId== 1 || stageId == 5){ //新增行动记录时，如果为线索1 或者成交客户5（再次购买），则改为沟通中2;
            cusStage.setStageId(2);
            customer.setCusStage(cusStage);
            add_cus_data(customer);
        }
    }
    /**
     * 新增销售机会时,客户所处阶段改变
     * @param cus:客户对象
     */
    public void stageChange2(Customer cus){
        //不管客户正在哪个阶段，只要新增了销售机会，都改为机会客户3;
        Customer customer = cusDao.findById(cus.getCustomerId()).get();
        CusStage cusStage = cusStageDao.findByStageId(3);
        customer.setCusStage(cusStage);
        add_cus_data(customer);
    }
    /**
     * 新增合同时,客户所处阶段改变
     * @param cus
     */
    public void stageChange3(Customer cus){
        Customer customer = cusDao.findById(cus.getCustomerId()).get();
        CusStage cusStage = cusStageDao.findByStageId(4);
        customer.setCusStage(cusStage);
        add_cus_data(customer);
    }
    /**
     * 合同状态改为已签订时,客户所处阶段改变
     * @param cus
     */
    public void stageChange4(Customer cus){
        Customer customer = cusDao.findById(cus.getCustomerId()).get();
        //改为成交客户5 ,合同数加一（成交客户是根据合同数 >0 查出）
        CusStage cusStage = cusStageDao.findByStageId(5);
        customer.setCusStage(cusStage);
        customer.setContractNum(customer.getContractNum()+1);
        add_cus_data(customer);
    }
    /**成交客户统计 按客户类型*/
    public Map<String,Object> cusNum(String activeName,Integer customerTypeId){return cusMapper.cusNum(activeName,customerTypeId);};
    public Map<String,Object> acReNum(String activeName,Integer customerTypeId){return cusMapper.acReNum(activeName,customerTypeId);};
    public Map<String,Object> oppoNum(String activeName,Integer customerTypeId){return cusMapper.oppoNum(activeName,customerTypeId);};
    public Map<String,Object> contractNum(String activeName,Integer customerTypeId){return cusMapper.contractNum(activeName,customerTypeId);};
    public  List<Map<String,Object>> staticData(Integer index){
        List<Map<String,Object>> statData= new ArrayList<>();
        if(1 == index ){
            this.allCusType().forEach(ca->{
                Map<String,Object> data = new HashMap<>();
                data.put("customerTypeId",ca.getCustomerTypeId());
                data.put("customerType",ca.getCustomerType());
                data.put("cusNum",this.cusNum("customer_type_id",ca.getCustomerTypeId()));
                data.put("acReNum",this.acReNum("customer_type_id",ca.getCustomerTypeId()));
                data.put("oppoNum",this.oppoNum("customer_type_id",ca.getCustomerTypeId()));
                data.put("contractNum",this.contractNum("customer_type_id",ca.getCustomerTypeId()));
                statData.add(data);
            });
        }else {
            this.allCusSource().forEach(ca->{
                Map<String,Object> data = new HashMap<>();
                data.put("customerTypeId",ca.getCustomerSourceId());
                data.put("customerType",ca.getCustomerSource());
                data.put("cusNum",this.cusNum("customer_source_id",ca.getCustomerSourceId()));
                data.put("acReNum",this.acReNum("customer_source_id",ca.getCustomerSourceId()));
                data.put("oppoNum",this.oppoNum("customer_source_id",ca.getCustomerSourceId()));
                data.put("contractNum",this.contractNum("customer_source_id",ca.getCustomerSourceId()));
                statData.add(data);
            });
        }
        return statData;
    };

    /**
     * 客户销售统计
     * @return
     */
    public List<Map<String,Object>> saleStatic(){return  cusMapper.saleStatic();};



    /**
     * 查询所有客户信息*/
    public List<Customer> allCusInfos(){return (List<Customer>) cusDao.findAll();}

    /**查询所有客户行为标签*/
    public List<Behavior> allBehaviors() {
       return (List<Behavior>) behaDao.findAll();
};


    /*添加客户信息*/
    public void add_cus_data( Customer customer) {
        System.out.println(customer);
        System.out.println("=====================");
        Customer cus = cusDao.save(customer);
        //有联系人则循环contact,赋值时，要setCustomer，执行contact新增
        if(customer.getContact().size() > 0){
            for (Contact c: customer.getContact()) {
                c.setCustomer(cus);
                add_contact(c);
            }
        }

    };
   /**添加联系人信息*/
    public void add_contact(Contact contact) {
        //新增/修改某客户联系人为主联系人时，先将他所有联系人is_main改为0，再修改
        if(contact.getIs_main() != null&&1 == contact.getIs_main()) {
            int customerId = contact.getCustomer().getCustomerId();
            List<Contact> contacts = hisLinkman(customerId);
            System.out.println("==========进了if");
            System.out.println(contacts);
            contacts.forEach(c ->{
                c.setIs_main(0);
                c.setContactType(c.getContactType());
                System.out.println(c.getContactType());
                conDao.save(c);
            });
        }
        System.out.println("==========没进if");
        conDao.save(contact);
    };


    /**添加员工行动记录*/
    public void addActionRecord(ActionRecord acrec){
        acreDao.save(acrec);
        System.out.println("进入service");
        for (BehaviorRecord b:acrec.getBehaviorRecordList() ){
            System.out.println(b);
            b.setActionRecord(acrec);
            addBehaviorRecord(b);
        }
    }
    /*添加客户行为记录*/
    public void addBehaviorRecord(BehaviorRecord bere){bereDao.save(bere); }

}
